﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Medianamik.UI
{
    public abstract class BaseTypePage : BasePage
    {
        private KeyValuePair<string, int?>? _fromSearchQuery;
        private KeyValuePair<string, int?> FromSearchQuery
        {
            get
            {
                if (!_fromSearchQuery.HasValue)
                {
                    var query = Request.QueryString["fromsearch"];
                    int p;
                    int? page = null;
                    if (int.TryParse(Request.QueryString["page"], out p))
                        page = p;
                    _fromSearchQuery = new KeyValuePair<string, int?>(query, page);
                }
                return _fromSearchQuery.Value;
            }
        }

        public bool CameFromSearchPage
        {
            get { return !string.IsNullOrEmpty(FromSearchQuery.Key); }
        }
        protected string SearchQuery
        {
            get { return FromSearchQuery.Key; }
        }
        protected int SearchResultPageIndex
        {
            get { return FromSearchQuery.Value.GetValueOrDefault(); }
        }
        protected bool HasSearchResultPageIndex
        {
            get { return FromSearchQuery.Value.HasValue && FromSearchQuery.Value.Value > 0; }
        }

        private string _searchURL;
        public string SearchURL
        {
            get 
            {
                if(_searchURL == null)
                {
                    _searchURL = "TypeSearchResults.aspx?q=" + SearchQuery;
                    if (HasSearchResultPageIndex)
                        _searchURL += "&p=" + SearchResultPageIndex; 
                }
                return _searchURL;
            }
        }

        protected string GetSearchURL(string baseUrl)
        {
            var url = baseUrl + 
                     (baseUrl.IndexOf('?') == -1 ? '?' : '&') + 
                     "fromSearch=" + 
                     SearchQuery;
            if (HasSearchResultPageIndex)
                url += "&page=" + SearchResultPageIndex;
            return url;
        }
    }
}
